/*
 * $Id: entity.c,v 1.2 1994/12/15 20:23:42 chris Exp $
 */

#include "entity.h"
#include <ctype.h>
#include <string.h>

static char *char_list[256] =
{
0, 0, 0, 0, 0, 0, 0, 0,			/* 0 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 8 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 16 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 24 */
0, 0, "quot", 0, 0, 0, "amp", 0,	/* 32 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 40 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 48 */
0, 0, 0, 0, "lt", 0, "gt", 0,		/* 56 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 64 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 72 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 80 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 88 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 96 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 104 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 112 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 120 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 128 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 136 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 144 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 152 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 160 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 168 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 176 */
0, 0, 0, 0, 0, 0, 0, 0,			/* 184 */
"Agrave", "Aacute", "Acirc", "Atilde", "Auml", "Aring", "AElig", "Ccedil",
"Egrave", "Eacute", "Ecirc", "Euml", "Igrave", "Iacute", "Icirc", "Iuml",
"ETH", "Ntilde", "Ograve", "Oacute", "Ocirc", "Otilde", "Ouml", 0,
"Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml", "Yacute", "THORN", "szlig",
"agrave", "aacute", "acirc", "atilde", "auml", "aring", "aelig", "ccedil",
"egrave", "eacute", "ecirc", "euml", "igrave", "iacute", "icirc", "iuml",
"eth", "ntilde", "ograve", "oacute", "ocirc", "otilde", "ouml", 0,
"oslash", "ugrave", "uacute", "ucirc", "uuml", "yacute", "thorn", "yuml"
};

/*
 * This function is passed the entity name and looks up
 * the value in the list.  If it is passed the full entity
 * name (ie. &amp;) it will isolate the name.  If the passed
 * string does not start with an ampersand, it will just do
 * a lookup.
 * If the string is not found the function will return -1;
 * Errors should be reported in the calling function.
 */
int
GetEntityValue(char *entity)
{
    char *semi = 0;
    int i;

    if (*entity == '&') {
	entity++;
	semi = strchr(entity, ';');
	if (semi)
	    *semi = '\0';
    }
    /* handle numeric references */
    if (*entity == '#') {
	int i = atoi(++entity);

	if ((i < 256) && (i >= 0))
	    return (i);
	else
	    return (-1);
    }
    /*
     * Now try character references
     * Could hash the list to speed this up.
     */
    for (i = 0; i < 256; i++) {
	if (char_list[i]) {
	    if (strcmp(entity, char_list[i]) == 0) {
		if (semi)
		    *semi = ';';
		return (i);
	    }
	}
    }
    /* failed to find it */
    if (semi)
	*semi = ';';
    return (-1);
}

/*
 * Return the string for an entity value.  Note that
 * if the value has no alpha string in our table, the
 * calling program should print the numeric representation.
 */
char *
GetEntityName(unsigned char value)
{
    return (char_list[value]);
}
